<?php

namespace App\Repository\UpThree;

use App\Api\Transfer;
use App\Repository\BaseRepository;
use App\Repository\GetWay\WayRepository;
use App\Repository\Order\OrderChannelRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Order\OrderRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use Illuminate\Support\Facades\Cache;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * 所有的判断都在这个文件里面
 * 例如 产品的判断 商品的判断
 * 提交到第三方的方法和判断信息
 */
class MainOrderRepostition_copy extends BaseRepository
{
    public function __construct(GoodsRepository $GoodsRepository, ProductRepository $ProductRepository, OrderProductRepository $OrderProductRepository, OrderChannelRepository $OrderChannelRepository, OrderRepository $OrderRepository)
    {
        $this->goodsModel = $GoodsRepository;
        $this->productModel = $ProductRepository;
        $this->orderProductModel = $OrderProductRepository;
        $this->channelModel = $OrderChannelRepository;
        $this->orderModel = $OrderRepository;
        $this->log = new Logger('ChinnelLog');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/ChinnelLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        // 记录的是 第三方成功了 但是本地失败了
        $this->logOrder = new Logger('orderLogs');
        $this->logOrder->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/orderLogs.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    // 提交到第三方数据
    public function orderSubmit($where)
    {
        $flag = true;
        $msg = '查询成功';
        // 查询到订单
        $resOrder = $this->orderModel->getOne($where);
        if (!$resOrder) {
            $flag = false;
            $msg = '未查询到订单信息';
        }
        /**
         * 根据订单的 product_code 提交到第三方
         * 查询第三方的信息
         */
        if ($flag) {
            $whereChannel = [
                'product_code' => $resOrder['product_code'],
                'shop_id' => $resOrder
            ];
            $resChannel = $this->channelModel->getAllProduct($whereChannel);
            if (!$resChannel) {
                $flag = false;
                $msg = '未查询到通道信息';
            }
        }
        if ($flag) {
            // 后面添加  参数不敢确定
            // if (!empty($resOrder->channel_error_josn)) {
            //     foreach ($resChannel as $key => $v) {

            //     }
            // }
        }
        if ($flag) {
            $model = new WayRepository();
            foreach ($resChannel as $key => $v) {
                $resWay = $model->getOne(['id' => $v['channel_id']]);
            }
        }
    }

    // 8.24 修改
    public function orderSubmit_back($data = array())
    {
        // var_dump(time());
        if (empty($data['goods_id']) && (empty($data['goods_code']) || empty($data['shop_id']))) {
            return $this->returnMsg(10001, '商品信息不能为空');
        }
        if (empty($data['name'])) {
            return $this->returnMsg(1, '用户名不能为空');
        }
        $name = strip_tags(trim($data['name']));
        $len = mb_strlen($name);
        if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·?]?[\x{4e00}-\x{9fa5}]+$/u', $name, $matchers)) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }
        if ($len < 2 || $len > 10) {
            return $this->returnMsg(10006, '用户名只能是两个及两个以上汉字');
        }

        //判断手机号
        if (empty($data['contact'])) {
            return $this->returnMsg(10007, '请输入您的手机号码');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $data['contact'])) {
            return $this->returnMsg(10007, '手机号错误，请重新查看');
        }
        if (empty($data['province'])) {
            return $this->returnMsg(10010, '缺少省份');
        }
        if (empty($data['city'])) {
            return $this->returnMsg(10011, '缺少市');
        }
        // if (!$request->has('area')) {
        //     return $this->returnMsg(10012, '缺少区');
        // }

        // $province = strip_tags(trim($data['province']));
        // $city = strip_tags(trim($data['city']));


        if (empty($data['address'])) {
            return $this->returnMsg(10013, '详细地址不能为空');
        }
        $lens = mb_strlen($data['address']);
        if (getStrLen($data['address']) < 2 || $lens > 50) {
            return $this->returnMsg(10006, '详细地址内容不小于2个汉字，请重新输入');
        }
        // 提交过来的字符串处理
        $data['identity'] = strtoupper(trim($data['identity'], ''));
        $data['address'] = (trim($data['address'], ''));
        $data['contact'] = (trim($data['contact'], ''));
        $data['name'] = (trim($data['name'], ''));
        $params['address'] = $data['address'];
        if (empty($data['identity'])) {
            return $this->returnMsg(10007, '身份证号码位数不正确，请检查');
        }
        $idcard = $data['identity'];

        if (!is_idcard($idcard)) {
            return $this->returnMsg(10007, '身份证号码不正确，请检查');
        }

        $data['orderno'] = !empty($data['dist_orderno']) ? ('HK_' . $data['dist_orderno']) : creatOrderNums('HK_');
        // 判断订单号是否存在
        $whereIsOrderNo = [
            'orderno' => $data['orderno'],
        ];
        $isOrder = $this->orderModel->getOne($whereIsOrderNo);
        if (!empty($isOrder)) {
            return $this->returnMsg(1002, '您的订单已存在,请前去更改');
        }
        // 使用缓存防止重复提交 或 重复记录数据
        $resCache = Cache::get($idcard . '_' . $data['contact']);
        $oneAdress = Cache::get($idcard . '_' . $data['contact'] . '_address');
        if (!empty($resCache) && ($oneAdress == $data['address'])) {
            if ($resCache == $data['address']) {
                // return $this->returnMsg(101, '已提交');
            }
            // return  $this->returnMsg(102, $resCache);
        }
        Cache::put($idcard . '_' . $data['contact'], $data['address']);
        Cache::put($idcard . '_' . $data['contact'] . '_address', $data['address']);
        // 参数验证完了
        $msg = '未查询到下单';
        $flag = true;
        //商品验证
        $whereGoods = [
            'status' => 0,
        ];
        if (!empty($data['goods_id'])) {
            $whereGoods['id'] = $data['goods_id'];
        }
        if (!empty($data['goods_code']) && !empty($data['shop_id'])) {
            $whereGoods['goods_code'] = $data['goods_code'];
            $whereGoods['shop_id'] = $data['shop_id'];
        }
        // var_dump($whereGoods);

        $resGoods = $this->goodsModel->getOne($whereGoods, ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'sup_shop_name', 'sup_shop_id', 'sup_goods_id', 'sup_goods_name', 'shop_id_str', 'shop_name_str', 'shop_id', 'shop_name']);
        if (!$resGoods) {
            $flag = false;
            $msg = '未查询到商品信息';
        }
        if (empty($data['shop_id'])) {
            $data['shop_id'] = $resGoods->shop_id;
        }
        $insertData = [];
        if ($flag) {
            // 添加还是修改 为了存储信息
            $insertData = [
                'orderno' => $data['orderno'],
                'dist_orderno' => !empty($data['dist_orderno']) ? $data['dist_orderno'] : '',
                'dist_id' => !empty($data['dist_id']) ? $data['dist_id'] : 0,
                'dist_name' => !empty($data['dist_name']) ? $data['dist_name'] : '',
                'contact_phone' => !empty($data['contact_phone']) ? $data['contact_phone'] : $data['contact'],
                'contact_name' => !empty($data['contact_name']) ? $data['contact_name'] : $data['name'],
                'pay_name' => $data['name'],
                'pay_phone' => $data['contact'],
                'pay_identity' => $idcard,
                'iccid' => !empty($data['number']) ? $data['number'] : '',
                'province' => !empty($data['numberProvince']) ? $data['numberProvince'] : '',
                'city' => !empty($data['numberCity']) ? $data['numberCity'] : '',
                'post_province' => !empty($data['province']) ? $data['province'] : '',
                'post_city' => !empty($data['city']) ? $data['city'] : '',
                'post_area' => !empty($data['area']) ? $data['area'] : '',
                'post_address' => !empty($data['address']) ? $data['address'] : '',
                'author_id' => !empty($data['author_id']) ? $data['author_id'] : '',
                'author_name' => !empty($data['author_name']) ? $data['author_name'] : '',
                'card_num' => !empty($data['card_num']) ? $data['card_num'] : '',
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
                'status' => 0,
                'shop_id' => $data['shop_id'],
                'shop_str' => $resGoods['shop_str'],
                'goods_id' => $resGoods['id'],
                'goods_name' => $resGoods['name'],
                'goods_code' => $resGoods['goods_code'],
                'product_id' => $resGoods['product_id'],
                'product_name' => $resGoods['product_name'],
                'product_code' => $resGoods['product_code'],
                'sup_goods_name' => $resGoods['sup_goods_name'],
                'shop_id_str' => $resGoods['shop_id_str'],
                'shop_name_str' => $resGoods['shop_name_str'],
                'sup_goods_id' => $resGoods['sup_goods_id'],
                'sup_goods_id_str' => $resGoods['sup_goods_id_str'],
                'sup_shop_id' => $resGoods['sup_shop_id'],
                'sup_shop_name' => $resGoods['sup_shop_name'],
                'source' => !empty($data['source']) ? $data['source'] : 0,
                'shop_name' => !empty($resGoods['shop_name']) ? $resGoods['shop_name'] : 0,
                'sell_name' => !empty($data['sell_name']) ? $data['sell_name'] : ''
            ];
        }
        // 产品验证开始
        $productId = !empty($resGoods->product_id) ? $resGoods->product_id : 0;
        // var_dump($productId, 222222222);
        $isValid = true;
        if (empty($resGoods->product_id)) {
            if (empty($resGoods->sup_goods_id_str)) {
                $isValid = false;
                $msgs = '商品出错,请联系管理员';
                // return $this->returnMsg(16, '商品出错,请联系管理员');
            }
            $productArr = explode('.', $resGoods->sup_goods_id_str);
            if (empty($productArr[1])) {
                $isValid = false;
                $msgs = '该产品无法下单,请联系商家';
                // return $this->returnMsg(17, '该产品无法下单,请联系商家');
            }

            $disGoods = $this->goodsModel->getOne(['id' => $productArr[1]], ['id', 'name', 'goods_code', 'product_name', 'product_id', 'product_code', 'shop_str', 'sup_goods_id_str', 'status']);
            if (empty($disGoods->product_id)) {
                $isValid = false;
                $msgs = '该产品无法下单,请联系商家';
                // return $this->returnMsg(18, '请联系供应商,未查询到产品信息');
            }
            if (!empty($disGoods->status) && $disGoods->status == 1) {
                $isValid = false;
                $msgs = '该产品无法下单,请联系商家';
                // return $this->returnMsg(19, '该产品已下架,请联系运营商');
            }
            $productId = $disGoods->product_id;
            $insertData['product_id'] = $disGoods['product_id'];
            $insertData['product_name'] = $disGoods['product_name'];
            $insertData['product_code'] = $disGoods['product_code'];
        }

        if ($flag) {
            $resProduct = $this->validProduct($productId, $data);
            // var_dump($resProduct);
            if (empty($resProduct['code']) || $resProduct['code'] != 200) {
                // $flag = false;
                $isValid = false;
                $msgs = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';
                // $insertData['status'] = 50;
                // $insertData['three_msg'] = !empty($resProduct['msg']) ? $resProduct['msg'] : '产品效验未过';

            }
            // $insertData['sup_orderno'] = !empty($resProduct['data']['order_id']) ? $resProduct['data']['order_id'] : ''; //渠道单号
            // $insertData['sup_id'] = !empty($resProduct['data']['channel_id']) ? $resProduct['data']['channel_id'] : ''; //渠道id
            // $insertData['sup_name'] = !empty($resProduct['data']['channel_name']) ? $resProduct['data']['channel_name'] : ''; //渠道名称
            // $insertData['three_msg'] = !empty($resProduct['data']['msg']) ? $resProduct['data']['msg'] : '';
            // $insertData['channel_error_josn'] = !empty($resProduct['data']['error']) ? $resProduct['data']['error'] : '';
        }
        if (!$isValid) {
            $insertData['status'] = 50;
            $insertData['three_msg'] = !empty($msgs) ? $msgs : '产品效验未过';
        }
        // 下单流程
        if ($flag) {
            $resOrder = $this->orderModel->add($insertData);
            if (empty($resOrder['code']) || $resOrder['code'] != 200) {
                //第三方提交成功了 但是存储数据库的时候 失败了 记录日志文件方便查看
                $this->logOrder->info('参数:' . json_encode($insertData) . '返回参数:' . json_encode($resOrder));
            }
        }
        // var_dump(time());
        if ($flag) {
            // 添加到队列中
            // $this->orderModel->upThree($insertData['orderno']);
            Cache::put($idcard . '_' . $data['contact'], '您已下过单,请更新信息在下单');
            return $this->returnMsg(200, '下单成功');
        }
        // 防止用户长时间提交
        Cache::put($idcard . '_' . $data['contact'], $msg);
        return $this->returnMsg(100, $msg);
    }

    //第三方的统一调用
    public function orderSubmitThree($method, $data)
    {
        $model = new Transfer();
        return $model->$method($data);
    }

    // 获取订单的信息
    public function getOrder($where)
    {
        // 查询订单数据
        $resOrder = $this->orderModel->getOne($where);
        if (!($resOrder)) {
            return $this->returnMsg(103, '未查询到订单');
        }
        return $this->returnMsg(200, '查询成功', $resOrder);
    }

    // 查询某个通道的详情
    public function getWay($data)
    {
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $data['model']]);
        if (!$resChannelModel) {
            return $this->returnMsg(102, '通道不存在');
        }
        $data['path'] = $resChannelModel->path;
        $data['url'] = $resChannelModel->url;
        $data['parame'] = $resChannelModel->parame;
        return $data;
    }

    //查询这个产品的所有应该提交的通道
    public function getProductChannel($data)
    {
        $where = [
            'product_code' => $data['product_code'],
        ];
        $resChannel = $this->channelModel->getAllProduct($where);
    }
}
